<template>
  <vxe-table-column
    :key="item.id"
    :field="item.dataIndex"
    :title="item.title"
    :show-overflow="item.ellipsis ? 'ellipsis':'tooltip'"
    :min-width="item.width || 200"
    :header-align="item.align || 'center'"
    :align="item.align || 'center'"
    :filters="item.showSearch === 1 || item.showSearch === 3 ? [] :undefined"
    :filter-render="{name: 'FilterTable'}"
    :footer-class-name="Number(item.sumKey) === 1 && !Number(item.isUpper)? 'sumKey':''"
    :header-class-name="Number(item.isUpper) === 1 && Number(item.sumKey) === 1 ? item.upperField:''"
    :tree-node="Number(item.isSpread) === 1"
  >
    <!-- <template #filter="{ column }">
      <input v-model="formTable().searchObj[item.dataIndex]" placeholder="按回车搜索" @keyup.enter="(value) => filterSeach(value, column)">
    </template> -->
    <template slot-scope="scope">
      <div v-if="item.componentType === 'text' || flag === 1 || formTable().tableType === 12|| !formTable().tableType">{{ scope.row[item.dataIndex] }}</div>
      <el-input
        v-else-if="item.componentType === 'input'"
        v-model="scope.row[item.dataIndex]"
        :placeholder="item.promptText || '请选择'"
        :type="item.isNumber ? 'Number' : 'text'"
        :readonly="!Number(item.edit)"
        @mousewheel.native.prevent
        @change="(value)=>inputChange(item, value, scope.rowIndex)"
      />
      <!-- <el-date-picker
        v-else-if="['yearDateSelect','dayDateSelect','monthDateSelect'].includes(item.componentType)"
        v-model="scope.row[item.dataIndex]"
        :type="item.componentType === 'yearDateSelect' ? 'year' : item.componentType === 'monthDateSelect' ? 'month' : 'date'"
        :format="item.componentType === 'yearDateSelect' ? 'yyyy' : item.componentType === 'monthDateSelect' ? 'yyyy-MM' : 'yyyy-MM-dd'"
        :value-format="item.componentType === 'yearDateSelect' ? 'yyyy' : item.componentType === 'monthDateSelect' ? 'yyyy-MM' : 'yyyy-MM-dd'"
        :placeholder="'请选择'+item.title"
        :readonly="!Number(item.edit)"
      /> -->
      <time-picker
        v-else-if="dataPicker(item)"
        v-model="scope.row[item.dataIndex]"
        :type="dataPicker(item).type"
        :value-format="dataPicker(item).format"
        :placeholder="item.promptText || '请选择'"
        :personal-style="{
          currentBorderRadius: '6px'
        }"
        :disabled="item.edit === 0"
        @blur="()=>getUrlRequire(item, scope.row[item.dataIndex], scope.rowIndex)"
      />
      <!-- 下拉框 -->
      <Select-Url
        v-else-if="['select', 'enterpriseIn', 'enterpriseList'].includes(item.componentType)"
        ref="selectUrl"
        :placeholder="item.promptText || '请选择'"
        :select-value="scope.row[item.dataIndex]"
        :item="item"
        :params="otherUrlRequire.length && otherUrlParams[scope.rowIndex] && otherUrlParams[scope.rowIndex][item.dataIndex] ? otherUrlParams[scope.rowIndex][item.dataIndex]:{}"
        :disabled="!Number(item.edit)"
        style="width: 100%;"
        :data-dataIndex="item.dataIndex"
        @change="(v) => selectChangeData(v,scope, item)"
        @changeItemOption="changeItemOption"
      />
      <SelectTree
        v-else-if="['treeSelect', 'treeSelectBot', 'enterpriseListTree', 'enterpriseInTree'].includes(item.componentType)"
        :select-value="scope.row[item.dataIndex]"
        :placeholder="item.promptText || '请选择'"
        :item="item"
        :disabled="!Number(item.edit)"
        @changeData="(data)=>treeSelectChangeData(data, scope, item)"
      />
      <!-- 输入&下拉 -->
      <transition
        v-else-if="item.componentType === 'toggleInputSelect'"
        mode="out-in"
        name="toggleIS"
      >
        {{ item.myToggleFlag }}
        <el-input
          v-if="item.myToggleFlag"
          ref="innerOper"
          v-model="scope.row[item.dataIndex]"
          :placeholder="item.promptText || '请输入'"
          :class="{'myEllipsis': item.ellipsis === 1}"
          :disabled="item.edit === 0"
          style="width: 100%;height: 100%;"
          :data-dataIndex="item.dataIndex"
          :title="scope.row[item.dataIndex]"
          :type="item.isNumber === 1 ? 'number' : 'text'"
          @mousewheel.native.prevent
          @change="v => inputChange(item, v, scope.rowIndex)"
        >
          <template #prefix>
            <div class="prefix_icon" @click="toggleFlag(item)">
              <div class="prefix_icon_bg" />
              <div>切换</div>
              <div>选择</div>
            </div>
          </template>
        </el-input>

        <Select-Url
          v-else
          ref="selectUrl"
          :title="scope.row[item.dataIndex]"
          :class="{'myEllipsis': item.ellipsis === 1}"
          :placeholder="item.promptText || '请选择'"
          :item="item"
          :disabled="item.edit === 0"
          style="width: 100%;height: 100%;"
          :data-dataIndex="item.dataIndex"
          :select-value="scope.row[item.dataIndex]"
          @change="v => selectChangeData(v, scope, item)"
          @changeItemOption="changeItemOption"
          @toggleChangeComponent="toggleFlag"
        >
          <template #prefix>
            <div class="prefix_icon" @click="toggleFlag(item)">
              <div class="prefix_icon_bg" />
              <div>切换</div>
              <div>输入</div>
            </div>
          </template>
        </Select-Url>
      </transition>
      <div v-else>{{ scope.row[item.dataIndex] }}</div>
    </template>
  </vxe-table-column>
</template>

<script>
import FilterTable from './FilterTable.vue';
import VXETable from 'vxe-table';
import TimePicker from '@/components/CommonForm/components/TimePicker';
import { digitUppercase } from '@/utils/utils';
import SelectUrl from '@/components/CommonForm/components/SelectUrl';
import SelectTree from '@/components/CommonForm/components/SelectTree';
import { dealRequestData } from '@/components/CommonForm/common';
import { getCommonData } from '@/api/reportCenter';
export default {
  name: 'TableCell',
  components: {
    SelectUrl,
    SelectTree,
    TimePicker,
    // eslint-disable-next-line vue/no-unused-components
    FilterTable
  },
  props: {
    item: {
      type: Object,
      default: () => ({})
    }
  },
  inject: {
    formTable: {
      default: () => ({})
    },
    updateFooter: {
      default: () => () => {}
    }
  },
  computed: {
    flag() {
      const { flag } = this.$route.query;
      return Number(flag);
    },
    otherUrlRequire() {
      return this.formTable().otherUrlRequire;
    },
    otherUrlDataindex() {
      return this.formTable().otherUrlDataindex;
    },
    otherUrlParams() {
      return this.formTable().otherUrlParams;
    }
  },
  created() {
    VXETable.renderer.add('FilterTable', {
      isFooter: false,
      // 筛选模板
      renderFilter(h, renderOpts, params) {
        return [
          <FilterTable params={params}/>
        ];
      }
    });
  },
  methods: {
    inputChange(item, value, index) {
      this.formTable().bodys[index][item.dataIndex] = Number(item.isNumber) ? Number(value) : value;
      const i = this.formTable().upperFieldList.findIndex(k => k === item.dataIndex);
      if (i !== -1) {
        this.formTable().bodys[index][this.formTable().isUpperList[i]] = digitUppercase(this.formTable().bodys[index][item.dataIndex]);
      }
      if (Number(item.sumKey) === 1) {
        this.updateFooter();
      }
      this.getUrlRequire(item, value, index);
    },
    selectChangeData(data, scope, item) {
      const { rowIndex } = scope;
      const { dataIndex, selectViewOptions, linkageFields } = item;
      // const { renderValue } = selectViewOptions;
      const { renderKey } = selectViewOptions;
      // this.formTable().bodys[rowIndex][dataIndex] = data[renderValue];
      this.formTable().bodys[rowIndex][dataIndex] = data[renderKey];
      linkageFields.length && linkageFields.forEach(itemC => {
        const linkObj = this.formTable().headers.find(v => v.dataIndex === itemC.key);
        let componentType, focusUrlParams;
        linkObj && (componentType = linkObj.componentType) && (focusUrlParams = linkObj.focusUrlParams);
        if (focusUrlParams && focusUrlParams.other) {
          this.getUrlRequire(item, data[itemC.value], rowIndex);
          return;
        }
        if (componentType === 'select' && linkObj && !linkObj.focusUrl) {
          // 需要先清空原有的数据
          this.formTable().bodys[rowIndex][itemC.key] = '';
          // headers.
          const arrOption = data[itemC.value].split(',');
          const arr = [];
          arrOption.forEach(itemCC => {
            arr.push({
              lable: itemCC,
              value: itemCC
            });
          });
          linkObj.opintion = arr;
          // 只有一个选项则默认为该选项
          if (arr.length === 1) {
            this.formTable().bodys[rowIndex][itemC.key] = arrOption[0];
          } else {
            this.formTable().bodys[rowIndex][itemC.key] = '';
          }
        } else {
          this.formTable().bodys[rowIndex][itemC.key] = data[itemC.value];
        }
      });
      this.$forceUpdate();
    },
    treeSelectChangeData(treeData, scope, item) {
      const { data, node } = treeData;
      const { rowIndex } = scope;
      const { dataIndex, selectViewOptions, linkageFields } = item;
      // const { renderValue } = selectViewOptions;
      const { renderKey } = selectViewOptions;
      this.formTable().bodys[rowIndex][dataIndex] = data[renderKey];
      // this.formTable().bodys[rowIndex][dataIndex] = data[renderValue];
      const nodeArr = [];
      const AddNodeshift = (arr) => {
        if (arr.parent) {
          nodeArr.unshift(arr.data);
          AddNodeshift(arr.parent);
        }
      };
      AddNodeshift(node);
      linkageFields.length && linkageFields.forEach(itemC => {
        if (!itemC.level) {
          const linkObj = this.formTable().headers.find(v => v.dataIndex === itemC.key);
          let componentType, focusUrlParams;
          linkObj && (componentType = linkObj.componentType) && (focusUrlParams = linkObj.focusUrlParams);
          if (focusUrlParams && focusUrlParams.other) {
            this.getUrlRequire(item, data[itemC.value], rowIndex);
            return;
          }
          if (componentType === 'select' && linkObj && !linkObj.focusUrl) {
            // 需要先清空原有的数据
            this.formTable().bodys[rowIndex][itemC.key] = '';
            // headers.
            const arrOption = data[itemC.value].split(',');
            const arr = [];
            arrOption.forEach(itemCC => {
              arr.push({
                lable: itemCC,
                value: itemCC
              });
            });
            linkObj.opintion = arr;
            // 只有一个选项则默认为该选项
            if (arr.length === 1) {
              this.formTable().bodys[rowIndex][itemC.key] = arrOption[0];
            } else {
              this.formTable().bodys[rowIndex][itemC.key] = '';
            }
          } else {
            this.formTable().bodys[rowIndex][itemC.key] = data[itemC.value];
          }
        } else {
          this.formTable().bodys[rowIndex][itemC.key] = nodeArr[itemC.level - 1][itemC.value];
        }
      });
    },
    filterSeach(v, column) {
      const { target: { value }} = v;
      const { property } = column;
      this.formTable.searchObj[property] = value;
      // this.formTable().searchReport();
      this.formTable().searchReport(this.formTable().searchObj);
    },
    changeItemOption(payload) {
      const { item, option } = payload;
      item.opintion = option;
      // item.opintion = option;
    },
    // 时间选择器类型
    dataPicker(item) {
      const { componentType } = item;
      const typesMap = {
        'yearDateSelect': {
          format: 'yyyy',
          type: 'year'
        },
        'monthDateSelect': {
          format: 'yyyy-MM',
          type: 'month'
        },
        'dayDateSelect': {
          format: 'yyyy-MM-dd',
          type: 'date'
        }
      };

      if (componentType in typesMap) {
        return typesMap[componentType];
      } else {
        return false;
      }
    },

    // 特殊url请求,item为当前操作对象,value为数据,index为行数
    getUrlRequire(item, value, index) {
      if (this.otherUrlRequire.length) {
        const { dataIndex } = item;
        if (this.otherUrlDataindex.includes(dataIndex)) {
          // 是other参数需要的dataindex
          // this.otherUrlRequire.forEach(v => {
          //   const { focusUrlParams: { other }} = v;
          //   const key = other[dataIndex].key;
          //   const arr = Object.keys(other);
          //   console.log(index);
          //   console.log(this.otherUrlParams);
          //   if (arr.includes(dataIndex)) {
          //     !this.otherUrlParams[index] && (this.otherUrlParams[index] = {}) && (this.otherUrlParams[index][v.dataIndex] = {});
          //     this.otherUrlParams[index][v.dataIndex][key] = value;
          //   }
          // });
          for (const i in this.otherUrlParams[index]) {
            let otheAllParams = true;
            this.otherUrlParams[index][i][dataIndex] && (this.otherUrlParams[index][i][dataIndex].value = value);
            for (const k in this.otherUrlParams[index][i]) {
              !this.otherUrlParams[index][i][k]['value'] && (otheAllParams = false);
            }
            const findObj = this.otherUrlRequire.find(v => v.dataIndex === i);
            if (otheAllParams && findObj && findObj.componentType !== 'select') {
              const otherKey = this.otherUrlParams[index][i];
              const endREquestPayload = dealRequestData(findObj.focusUrlParams, otherKey);
              getCommonData(endREquestPayload, findObj.focusUrl).then(({ data }) => {
                const { success, message } = data;
                if (success) {
                  this.formTable().bodys.forEach(v => {
                    v[findObj.dataIndex] = data.data.result;
                  });
                } else {
                  this.formTable().bodys.forEach(v => {
                    v[findObj.dataIndex] = '';
                  });
                  this.$message.error(message);
                }
              });
            }
          }
          this.$forceUpdate();
        }
      }
    },
    toggleFlag(item) {
      this.$set(item, 'myToggleFlag', !item.myToggleFlag);
      this.$forceUpdate();
    }
  }
};
</script>

<style lang="scss" scoped>
.myEllipsis /deep/ input {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.prefix_icon {
  cursor: pointer;
  font-size: 12px;
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  // overflow: hidden;

  > div {
    height: 33%;
    position: relative;
    // top: -5px;
    color: #fff;
    // position: absolute;
  }
    .prefix_icon_bg {
      height: 35px;
      width: 30px;
      position: absolute;
      background-color: #1492FF;
      top: 2px;
      border-radius: 2px;
    }
}
</style>
